package com.demo.springmvc底层演示.异常处理;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

public class Test {
	
	public static void main(String[] args) throws Exception {
		ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver();
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>() {{
			add(new MappingJackson2HttpMessageConverter());
		}};
		resolver.setMessageConverters(messageConverters);
		// 添加一些默认的Controller方法的入参、出参解析器
		resolver.afterPropertiesSet();
		
		MockHttpServletRequest request = new MockHttpServletRequest();
		MockHttpServletResponse response = new MockHttpServletResponse();
		HandlerMethod handlerMethod = new HandlerMethod(new Controller1(),  Controller1.class.getMethod("foo"));
		Exception e = new ArithmeticException("被零除");
		// 这样就可以知道异常是在Controller1类发生的，然后找到@ExceptionHandler，然后进行异常匹配，如果一致，就可以执行@ExceptionHandler注解的方法
		resolver.resolveException(request, response, handlerMethod, e);
		
		System.out.println(new String(response.getContentAsByteArray(), "utf-8"));
	}
	
	static class Controller1 {
		public void foo() {
			
		}
		
		@ExceptionHandler
		@ResponseBody
		public Map<String, Object> handle(ArithmeticException e){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("error", e.getMessage());
			return map;
		}
	}

}
